package com.mofofa.maozy.utils.analytics.util

import android.app.Application
import com.appsflyer.*
import com.mofofa.maozy.utils.analytics.bean.ParamAppsflyerInstall
import com.mofofa.maozy.utils.analytics.bean.ParamAppsflyerS2S
import com.mofofa.maozy.utils.analytics.event.IAnalyticsEvent
import com.mofofa.maozy.utils.analytics.http.HttpHelper
import com.google.gson.Gson
import com.mofofa.maozy.ProjectApplication
import com.mofofa.maozy.ProjectConfig
import com.mofofa.maozy.network.ApiUrl
import com.mofofa.maozy.utils.AppConfigUtil

object AppsflyerUtil {

    /** Appsflyer 安装数据回传json字符串 */
    private var mAFConversionData: MutableMap<String, Any>? = null

    /**
     * 初始化Appsflyer模块
     * 按配置需要来初始化
     *
     * @param context Application
     * @param afDevKey af dev key
     */
    fun init(context: Application, afDevKey: String) {
        if (afDevKey.isNotBlank()) {
            val conversionListener = object : AppsFlyerConversionListener {
                override fun onConversionDataSuccess(p0: MutableMap<String, Any>?) {
                    //保存af 转化数据
                    mAFConversionData = p0
                    val pathList =
                        AppConfigUtil.getMaozyValidMaozyCountrysMaozyPaths()
                    saveInstallInfo(pathList)
                    saveS2SInfo(pathList)
                }

                override fun onConversionDataFail(p0: String?) {
                    println("AF onConversionDataFail")
                }

                override fun onAppOpenAttribution(p0: MutableMap<String, String>?) {
                    println("AF onAppOpenAttribution")
                }

                override fun onAttributionFailure(p0: String?) {
                    println("AF onAttributionFailure $p0")
                }
            }
            saveUserCUID()
            AppsFlyerLib.getInstance().init(afDevKey, conversionListener, context)
            AppsFlyerLib.getInstance().start(context)
        }
    }

    /**
     * 打点
     *
     * @param event 事件名
     */
    fun addEvent(event: IAnalyticsEvent) {
        try {
            when (event) {
                IAnalyticsEvent.AT_REGISTER -> {
                    val map = mutableMapOf<String, Any>()
                    map[AFInAppEventParameterName.REGSITRATION_METHOD] = "InApp"
                    AppsFlyerLib.getInstance()
                        .logEvent(
                            ProjectApplication.instance,
                            AFInAppEventType.COMPLETE_REGISTRATION, map
                        )
                }
                IAnalyticsEvent.AT_BASIC -> {
                    val map = mutableMapOf<String, Any>()
                    map[AFInAppEventParameterName.CONTENT_TYPE] =
                        IAnalyticsEvent.AT_BASIC.name
                    map[AFInAppEventParameterName.LEVEL] = "1"
                    map[AFInAppEventParameterName.SCORE] = "1"
                    AppsFlyerLib.getInstance()
                        .logEvent(
                            ProjectApplication.instance,
                            AFInAppEventType.LEVEL_ACHIEVED,
                            map
                        )
                }
                IAnalyticsEvent.AT_WORK -> {
                    val map = mutableMapOf<String, Any>()
                    map[AFInAppEventParameterName.CONTENT_TYPE] =
                        IAnalyticsEvent.AT_WORK.name
                    map[AFInAppEventParameterName.CONTENT_ID] =
                        IAnalyticsEvent.AT_WORK.name
                    map[AFInAppEventParameterName.MAX_RATING_VALUE] = "5"
                    AppsFlyerLib.getInstance()
                        .logEvent(ProjectApplication.instance, AFInAppEventType.RATE, map)
                }
                IAnalyticsEvent.AT_CONTACT -> {
                    val map = mutableMapOf<String, Any>()
                    map[AFInAppEventParameterName.CONTENT_TYPE] =
                        IAnalyticsEvent.AT_CONTACT.name
                    map[AFInAppEventParameterName.SEARCH_STRING] =
                        IAnalyticsEvent.AT_CONTACT.name
                    map[AFInAppEventParameterName.SUCCESS] =
                        IAnalyticsEvent.AT_CONTACT.name
                    AppsFlyerLib.getInstance()
                        .logEvent(ProjectApplication.instance, AFInAppEventType.SEARCH, map)
                }
                IAnalyticsEvent.AT_REV_CARD -> {
                    val map = mutableMapOf<String, Any>()
                    map[AFInAppEventParameterName.CONTENT_TYPE] =
                        IAnalyticsEvent.AT_REV_CARD.name
                    map[AFInAppEventParameterName.CONTENT_ID] =
                        IAnalyticsEvent.AT_REV_CARD.name
                    map[AFInAppEventParameterName.CONTENT] =
                        IAnalyticsEvent.AT_REV_CARD.name
                    map[AFInAppEventParameterName.CURRENCY] = "USD"
                    map[AFInAppEventParameterName.PRICE] = "5000"
                    AppsFlyerLib.getInstance()
                        .logEvent(
                            ProjectApplication.instance,
                            AFInAppEventType.CONTENT_VIEW,
                            map
                        )
                }
                IAnalyticsEvent.AT_LOAN_APPLY -> {
                    val map = mutableMapOf<String, Any>()
                    map[AFInAppEventParameterName.REVENUE] = 1
                    map[AFInAppEventParameterName.CURRENCY] = "USD"
                    map[AFInAppEventParameterName.CONTENT_ID] = "Apply_ID"
                    map[AFInAppEventType.ORDER_ID] = System.currentTimeMillis().toString()
                    map[AFInAppEventParameterName.RECEIPT_ID] = "9277"
                    map[AFInAppEventParameterName.QUANTITY] = 1
                    map[AFInAppEventParameterName.CONTENT_TYPE] =
                        IAnalyticsEvent.AT_LOAN_APPLY.name
                    AppsFlyerLib.getInstance()
                        .logEvent(ProjectApplication.instance, AFInAppEventType.PURCHASE, map)
                }
                IAnalyticsEvent.AT_REPAY -> {
                    val map = mutableMapOf<String, Any>()
                    map[AFInAppEventParameterName.SUCCESS] = true
                    map[AFInAppEventParameterName.TUTORIAL_ID] = "repay_ID"
                    map[AFInAppEventParameterName.CONTENT] = "repay"
                    map[AFInAppEventParameterName.CONTENT_TYPE] =
                        IAnalyticsEvent.AT_REPAY.name
                    AppsFlyerLib.getInstance()
                        .logEvent(
                            ProjectApplication.instance,
                            AFInAppEventType.TUTORIAL_COMPLETION,
                            map
                        )
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 保存用户cuid
     */
    fun saveUserCUID() {
        try {
            val lastCuid =
                AppsFlyerProperties.getInstance().getString(AppsFlyerProperties.APP_USER_ID)
            if (lastCuid.isNullOrEmpty()) {
                val tempFlyerUID =
                    AppsFlyerLib.getInstance().getAppsFlyerUID(ProjectApplication.instance)
                val appsFlyerUID = tempFlyerUID ?: System.currentTimeMillis().toString()
                val cuid = "${ProjectConfig.MAOZY_Product}_${appsFlyerUID}"
                AppsFlyerLib.getInstance().setCustomerUserId(cuid)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 保存Appsflyer 安装信息
     */
    fun saveInstallInfo(targetUrlList: List<String>) {
        mAFConversionData?.let { data ->
            try {
                val dataJsonString = Gson().toJson(data).trim()
                val params = ParamAppsflyerInstall(sessionData = dataJsonString)
                val body = Gson().toJson(params).trim()
                println("====== $targetUrlList")

                //传多国时，里触发多次
                val apiPath = ApiUrl.MAOZY_PATH_APPSFLYER_INSTALL
                targetUrlList.forEach { host ->
                    val pathFormat =
                        if (host.endsWith(apiPath)) host else (host + apiPath)
                    HttpHelper.postData(pathFormat, body)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    /**
     * 保存Appsflyer s2s信息
     */
    fun saveS2SInfo(targetUrlList: List<String>) {
        try {
            val params = ParamAppsflyerS2S()
            val body = Gson().toJson(params).trim()
            println("====== $targetUrlList")

            //传多国时，里触发多次
            val apiPath = ApiUrl.MAOZY_PATH_APPSFLYER_S2S
            targetUrlList.forEach { host ->
                val pathFormat =
                    if (host.endsWith(apiPath)) host else (host + apiPath)
                HttpHelper.postData(pathFormat, body)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}